package com.tuocent.dagv2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.entity.LoginUserInfo;
import com.tuocent.dagv2.common.utils.SnowFlakeID;
import com.tuocent.dagv2.common.utils.redis.RedisCache;
import com.tuocent.dagv2.constant.PublicConst;
import com.tuocent.dagv2.entity.ArchivesReceive;
import com.tuocent.dagv2.entity.Projects;
import com.tuocent.dagv2.entity.Task;
import com.tuocent.dagv2.mapper.ArchivesReceiveMapper;
import com.tuocent.dagv2.service.IArchivesReceiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuocent.dagv2.service.IProjectsService;
import com.tuocent.dagv2.service.ITaskService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 档案接收 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2024-05-04
 */
@Service
public class ArchivesReceiveServiceImpl extends ServiceImpl<ArchivesReceiveMapper, ArchivesReceive> implements IArchivesReceiveService {
    @Resource
    private SnowFlakeID snowFlakeID;
    @Resource
    private RedisCache redis;
    @Autowired
    private IProjectsService projectsService;
    @Autowired
    private ITaskService taskService;

    @Override
    public String archivesReceive(Model model) {
        List<Projects> projectsList = projectsService.list(new QueryWrapper<Projects>().eq("is_del", "0"));
        model.addAttribute("projectsList", projectsList);
        return "/workflow/archivesReceive";
    }

    @Override
    public AjaxResult getArchivesReceiveData(Map<String, Object> params) {
        int limit = PublicConst.DEF_LIMIT;
        int page = PublicConst.DEF_PAGE;
        QueryWrapper<ArchivesReceive> qw = new QueryWrapper<ArchivesReceive>()
                .eq("is_del", "0")
                .orderByAsc("status")
                .orderByDesc("batch_code");
        for (String key : params.keySet()) {
            switch (key) {
                case "limit":
                    limit = Integer.parseInt(params.get(key).toString());
                    break;
                case "page":
                    page = Integer.parseInt(params.get(key).toString());
                    break;
                default:
                    String value = params.get(key).toString().trim();
                    if (!value.isEmpty()) {
                        qw.eq(key, value);
                    }
                    break;
            }
        }
        Page<ArchivesReceive> archivesReceiveData = page(new Page<>(page, limit), qw);
        return AjaxResult.success(archivesReceiveData.getRecords(), archivesReceiveData.getTotal());
    }

    @Override
    public String setArchivesReceive(Model model, String pid, String tid, String id) {
        ArchivesReceive data = getById(id);
        if (data == null) {
            data = new ArchivesReceive();
            data.setPid(pid);
            data.setTid(tid);
            data.setBatchCode(getBatchCode(pid, tid));
            data.setOutDate(LocalDate.now());
        }
        model.addAttribute("data", data);
        return "/workflow/setArchivesReceive";
    }

    @Override
    public AjaxResult saveArchivesReceiveData(HttpSession session, ArchivesReceive data) {
        if (data == null) {
            return AjaxResult.error("没有可保存的数据");
        }
        LoginUserInfo loginUser = redis.get(session.getId());
        QueryWrapper<ArchivesReceive> qw = new QueryWrapper<ArchivesReceive>()
                .eq("batch_code", data.getBatchCode())
                .eq("pid", data.getPid());
        if (data.getId() == null || data.getId().isEmpty()) {
            data.setId(snowFlakeID.getId());
            data.setIsDel("0");
            data.setStatus("0");
            data.setCreator(loginUser.getUserName());
            data.setCreateTime(LocalDateTime.now());

            Task task = taskService.getById(data.getTid());
            data.setClassify(task.getArchivesClassifyId());
        } else {
            qw.ne("id", data.getId());
        }
        if (count(qw) > 0) {
            return AjaxResult.error("该批次号已存在，请重新输入");
        }
        return saveOrUpdate(data) ? AjaxResult.success("保存数据成功") : AjaxResult.error("保存数据失败");
    }

    @Override
    public AjaxResult delArchivesReceive(HttpSession session, Map<String, Object> params) {
        //需要重新认证
        LoginUserInfo loginUser = redis.get(session.getId());
        
        String id = params.getOrDefault("id", "").toString();
        UpdateWrapper<ArchivesReceive> uw = new UpdateWrapper<ArchivesReceive>().set("is_del", "1").eq("id", id);
        return update(uw) ? AjaxResult.success("删除接收批次成功") : AjaxResult.error("删除批次失败");
    }

    public String getBatchCode(String pid, String tid) {
        long idx = count(new QueryWrapper<ArchivesReceive>()
                .eq("pid", pid)
                .eq("tid", tid)
                .eq("date(create_time)", LocalDate.now())) + 1;
        StringBuilder code = new StringBuilder(String.valueOf(idx));
        for (int i = 1; code.length() < 3; i++) {
            code.insert(0, "0");
        }
        return LocalDate.now().format(PublicConst.dateFormatStr) + code;
    }
}
